import React from 'react';
import {inject, observer} from 'mobx-react';
import {toJS} from 'mobx';
import {Spin, Pagination} from 'antd';
import {WeaNewScroll, WeaDialog, WeaTools, WeaAvatar } from 'ecCom';
const { sendMsg } = WeaTools;
const Base64 = ecCom.WeaTools.Base64;
import {WeaLocaleProvider} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;

// import Apps from 'weaSmallApp';
// const AppCom = Apps.com;
// const SendSms = AppCom.SendSms;
//
// import Workplan from 'weaWorkplan';
// const WorkPlanCreate = Workplan.com.WorkPlanCreate;
const store = [
  'weesoSeachSetStore',
  'weesoStore',
  'routing'
];
@inject(...store)
@observer
export default class CommonContent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      smsVisible: false,
      workPlanVisible: false,
      id: '',
    }
  }

   componentDidMount() {
    let pageuuid = this.props.routing&&this.props.routing.location&&this.props.routing.location.query&&this.props.routing.location.query.page_uuid;
    const { getBaseData, setUrlParams } = this.props.weesoStore;
    let urlParms =  this.props.routing && this.props.routing.location && this.props.routing.location.query;
    urlParms = toJS(urlParms);
    if(pageuuid) {
      setUrlParams(urlParms,() => {
        getBaseData(undefined, undefined, undefined, pageuuid);
      });
    } else {
      setUrlParams(urlParms,() => {
        getBaseData();
      });
    }
    if (!window.weaWorkplan) {
      eventRegister.loadModule('f_workplan', ()=>{
        this.props.weesoStore.setWPLoaded(true)
      }, ()=>{})
    } else {
      this.props.weesoStore.setWPLoaded(true)
    }
    if (!window.weaSmallApp) {
      eventRegister.loadModule('f_smallApp', ()=>{
        this.props.weesoStore.setSMLoaded(true)
      }, ()=>{})
    } else {
      this.props.weesoStore.setSMLoaded(true)
    }

  }
  
  render() {
    const {weesoStore} = this.props;
    let {searchResult, emptyResult, page, searchDatas, supportSkipSearch} = weesoStore;
    searchDatas = toJS(searchDatas);
    let
      maxPerPage = searchDatas.maxPerPage || '',
      recordCount = searchDatas.recordCount || '';
    
    let paginationProps = supportSkipSearch ? {
      showQuickJumper: true,
      showTotal: total => getLabel('514163','共${num}页').replace('${num}', Math.ceil(total/maxPerPage)),
    } : {
      className: "esearch-pagination-customize",
    };
      const hidesearch = this.props.hidesearch || '0';
      let topStyle = {};
      if (hidesearch === '1') {
          topStyle = { paddingTop: '10px', paddingLeft:'10px'};
      }
    return (
      <div className="result-content" style={topStyle}>
        <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@4go8kr`} height={'100%'}>
            {emptyResult ?
              <div className="wea-content-empty">
                <div dangerouslySetInnerHTML={{__html: emptyResult}}/>
              </div> :
              <div>
                {
                  searchResult && searchResult.length != 0 && searchResult.map((item,index) => {
                    if (item.schema == 'ROBOT') {
                      return (
                        <div className="robot-content">
                          <iframe
                            name={item.head.name}
                            width={item.head.width || '100%'}
                            height={item.head.height}
                            src={item.head.iframe} frameborder="0">
                          </iframe>
                        </div>
                      )
                    } else if (item.schema == 'RSC') {
                      return (
                        <div className="content">
                          <div className="content-img">
                            {item && item.head && item.head.id != '' ? <WeaAvatar ecId={`${this && this.props && this.props.ecId || ''}_WeaAvatar@6jng21@${index}`} userId={item.head.id} /> :
                              <img src={item.head.imageUrl}/> 
                            }
                          </div>
                          <div className="content-detail">
                            <p className="detail-msg">
                                {this.getHrmNameContent(item,weesoStore,index)}
                              <span className="detail-msg-gender">{item.head.gender}</span>
                              <img className="detail-addrs" src="/fullsearch/img/unit_wev8.png"/>
                              <span dangerouslySetInnerHTML={{__html: item.head.org}}/>
                            </p>
                            {
                              item.foot && item.foot.info && item.foot.info.length != 0 && item.foot.info.map(i => {
                                  return (
                                    <p className="content-foot">
                                      <span>{i.key}：</span>
                                      <p>{i.value}</p>
                                    </p>
                                  )
                                }
                              )
                            }
                          </div>
                          {this.getCommonComtent(item.head)}
                        </div>
                      )
                    } else {
                      const other = item.other ? JSON.parse(item.other) : undefined;
                      return (
                        <div className="common-content">
                          <p className="common-content-top wea-f14 ">
                            <span dangerouslySetInnerHTML={{__html: item.head && item.head.type}}/>
                            <a className="content-link"
                               target="_Blank"
                               href={item.head && item.head.titlelink}
                               dangerouslySetInnerHTML={{__html: item.head && (weesoStore.defaultKey == 'CONTENT' ? Base64.decode(item.head.title) : item.head.title)}}
                               onClick={() => {this.userHabitCollect(item.head.titlelink, index)}}
                            />
                            { other && (other.attachFile === true) && <i style={{ marginLeft: 5,color: '#4d7ad8'}} className="icon-coms-currency-Enclosure" /> }
                          </p>
                          <p dangerouslySetInnerHTML={{__html: item.head && (weesoStore.defaultKey == 'CONTENT' ? Base64.decode(item.contents.contents) : item.contents.contents)}}/>
                          {
                            item.foot && item.foot.info && item.foot.info.length != 0 && item.foot.info.map(i => {
                                return (
                                  <p className="conmon-content-foot">
                                    <span>{i.key}：</span>
                                    <p>{i.value}</p>
                                  </p>
                                )
                              }
                            )
                          }
                        </div>
                      )
                    }
                  })
                }
                {searchResult && searchResult.length != 0 && recordCount > maxPerPage &&
                <div className="result-pagination">
                  <Pagination ecId={`${this && this.props && this.props.ecId || ''}_Pagination@k5a9pv`}
                    {...paginationProps}
                    hideFirstLast
                    defaultCurrent={Number(page)}
                    pageSize = {maxPerPage}
                    total={recordCount}
                    onChange={(cur) => {
                      weesoStore.setState({page: String(cur)});
                      const { filterParams } = this.props.weesoSeachSetStore;
                      let p = { page_search_json: JSON.stringify(filterParams())};
                      weesoStore.preSearch(p);
                    }}/>
                </div>}
              </div>
            }
        </WeaNewScroll>

       {this.props.weesoStore.wpLoaded && window.weaWorkplan && window.weaWorkplan.com && window.weaWorkplan.com.WorkPlanCreate &&
          <window.weaWorkplan.com.WorkPlanCreate ecId={`${this && this.props && this.props.ecId || ''}_undefined@51m1rp`} type="create"
                          visible={this.state.workPlanVisible}
                          doClose={() => {this.setState({workPlanVisible: false})}}
                          onlyClose={() => {this.setState({workPlanVisible: false})}}
                          isCustom={true}
                          selectUser={this.state.id}
                          createConditionParams={[]}
          />
        }


         <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@0fruzs`} visible={this.state.smsVisible}
                   title={getLabel(125977,"发送短信")}
                   icon="icon-coms-message"
                   style={{width: 800, height: 500}}
                   onCancel = {() => {this.setState({smsVisible: false})}}
        >
        {this.props.weesoStore.smLoaded && window.weaSmallApp && window.weaSmallApp.com && window.weaSmallApp.com.SendSms &&
          <window.weaSmallApp.com.SendSms ecId={`${this && this.props && this.props.ecId || ''}_undefined@0g85qw`} isCus = {true} hrm={this.state.id}/>
        }
        </WeaDialog>
      </div>
    )
  }

  //用户使用习惯记录
  userHabitCollect = (link, index) => {
    const {weesoStore} = this.props;
    weesoStore.userDatas.push({
      type: 'eventTrack',
      key: weesoStore.inputValue,
      contentType: weesoStore.defaultKey,
      page: weesoStore.page,
      searchType: weesoStore.defalutMoreKey,
      sortField:  weesoStore.sortValue,
      timeStamp: String(new Date().getTime()),
      index: String(index),
      eventUrl: link
    })
  }

  getHrmNameContent=(item,weesoStore,index)=>{
      if(item.head.titlelink&&item.head.titlelink!=''){
          return(
              <a target="_Blank"
                 href={item.head.titlelink}
                 onClick={() => {this.userHabitCollect(item.head.titlelink,index)}}
              >
                  <span dangerouslySetInnerHTML={{__html: weesoStore.defaultKey == 'CONTENT' ? Base64.decode(item.head.title) : item.head.title}}></span>
              </a>
          );
      }else{
          return(
              <span>
                  <span dangerouslySetInnerHTML={{__html: weesoStore.defaultKey == 'CONTENT' ? Base64.decode(item.head.title) : item.head.title}}></span>
              </span>
          );
      }
  }

  getCommonComtent = (chooseValues) => {
    return (
      <div className="content-choose">
        <div>
            { (chooseValues.hideMessage==undefined||chooseValues.hideMessage!='1')&&
            <a className="choose-icon" title={getLabel(384220,"发送消息")}
               onClick={() => sendMsg(chooseValues && chooseValues.id, 0, '', '')}>
                <i className="icon-coms-Send-message"></i>
            </a>
            }
            {
                (chooseValues.hideSms==undefined||chooseValues.hideSms!='1')&&
                <a className="choose-icon" title={getLabel(125977,"发送短信")}
                   onClick={() => {this.setState({smsVisible: true, id: chooseValues.id})}}>
                    <i className="icon-coms-message-o"></i>
                </a>
            }

            {
                (chooseValues.hideEmail==undefined||chooseValues.hideEmail!='1')&&
                <a className="choose-icon" title={getLabel(2051,"发送邮件")}
                   onClick={() => window.open(`/spa/email/static/index.html#/main/email/new?isInternal=1&internalto=${chooseValues && chooseValues.id}`)}>
                    <i className="icon-coms-Send-emails"></i>
                </a>
            }

            {
                (chooseValues.hideWorkPlan==undefined||chooseValues.hideWorkPlan!='1')&&
                <a className="choose-icon" title={getLabel(18481,"新建日程")}
                   onClick={() => {this.setState({workPlanVisible: true, id: chooseValues.id})}}>
                    <i className="icon-coms-New-schedule-o"></i>
                </a>
            }
        </div>
      </div>
    )
  }
}
